package com.bolt.auth.security.auth.server.component;

import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.*;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.stereotype.Service;

@Service
public class CustomResponseExceptionTranslator extends DefaultWebResponseExceptionTranslator {

    @Override
    public ResponseEntity <OAuth2Exception> translate(Exception e) throws Exception {
        OAuth2Exception oAuth2Exception;
        if (e instanceof InvalidGrantException || e instanceof BadCredentialsException || e instanceof UsernameNotFoundException) {
            oAuth2Exception = new InvalidGrantException(e.getMessage(), e);
        } else if (e instanceof InternalAuthenticationServiceException) {
            oAuth2Exception = new InvalidGrantException(e.getMessage(), e);
        } else if (e instanceof RedirectMismatchException) {
            oAuth2Exception = new InvalidGrantException(e.getMessage(), e);
        } else if (e instanceof InvalidScopeException) {
            oAuth2Exception = new InvalidGrantException(e.getMessage(), e);
        } else {
            oAuth2Exception = new UnsupportedResponseTypeException("服务内部错误", e);
        }
        ResponseEntity <OAuth2Exception> response = super.translate(oAuth2Exception);
        ResponseEntity.status(oAuth2Exception.getHttpErrorCode());
        return response;
    }
};


 